package com.gitee.xqlr.graphql.client.request.result;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杜文康
 * @version 1.0
 * @date 2019/8/12 15:18
 */
public class RetAttr {
    private final String name;

    private final Map<String, RetAttr> retAttrMap = new HashMap<String, RetAttr>();

    public static RetAttr create() {
        return new RetAttr();
    }

    public RetAttr() {
        name = "";
    }

    private RetAttr(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public RetAttr addRetAttrs(String... retAttr) {
        for (String field : retAttr) {
            List<String> list = Arrays.asList(field.split("\\."));
            int size = list.size();
            if (size == 1) {
                this.addRetAttrs(new RetAttr(field));
            } else {
                RetAttr last = null;
                //倒序遍历构建层级关系
                for (int i = size - 1; i >= 0; i--) {
                    String name = list.get(i);
                    last = last == null ? new RetAttr(name) : new RetAttr(name).addRetAttrs(last);
                }
                if (last != null) {
                    this.addRetAttrs(last);
                }
            }
        }
        return this;
    }

    /**
     * 添加返回内容
     *
     * @param retAttrs result data names
     * @return ResultAttribute
     */
    public RetAttr addRetAttrs(RetAttr... retAttrs) {
        if (retAttrs != null && retAttrs.length > 0) {
            for (RetAttr attribute : retAttrs) {
                RetAttr exist = retAttrMap.get(attribute.name);
                if (exist != null) {
                    for (RetAttr value : attribute.retAttrMap.values()) {
                        exist.addRetAttrs(value);
                    }
                } else {
                    retAttrMap.put(attribute.name, attribute);
                }
            }
        }
        return this;
    }

    @Override
    public String toString() {
        if (retAttrMap.size() == 0) {
            return name;
        }
        StringBuilder tmp = new StringBuilder(name + "{");
        boolean first = true;
        for (RetAttr ra : retAttrMap.values()) {
            if (first) {
                first = false;
                tmp.append(ra.toString());
            } else {
                tmp.append(" ").append(ra.toString());
            }
        }
        String content = tmp.append("}").toString();
        if ("".equals(name)) {
            //移除最外层大括号
            content = content.substring(1, content.length() - 1);
        }
        return content.trim();
    }
}
